package com.lujianfei.netease_android_shareelement.ui

import android.os.Bundle
import android.transition.Fade
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lujianfei.netease_android_shareelement.R
import com.lujianfei.netease_android_shareelement.adapter.ShareElementAdapter
import com.lujianfei.netease_android_shareelement.beans.ListEntity
import com.lujianfei.netease_android_shareelement.widget.DetailTransition


class ShareElementListFragment : Fragment() {

    private val adapter = ShareElementAdapter()
    private val list = arrayListOf<ListEntity>()
    private var recyclerview: RecyclerView? = null
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.activity_share_element, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        recyclerview = view?.findViewById(R.id.recyclerview)
        recyclerview?.layoutManager = LinearLayoutManager(context)
        initData()
        adapter.onClickListener = { view, position ->
            val bean = list[position]
            startDetail(bean, view)
        }
    }

    private fun startDetail(bean: ListEntity, view: View) {
        val fragmentDetail = ShareElementDetailFragment()
        val icon = view.findViewById(R.id.icon) as View
        val title = view.findViewById(R.id.title) as View
        val bundle = Bundle()
        bundle.putParcelable(ShareElementDetailFragment.KEY_DATA, bean)
        fragmentDetail.arguments = bundle
        fragmentDetail.enterTransition = Fade()
        exitTransition = Fade()
        fragmentDetail.sharedElementEnterTransition = DetailTransition()
        fragmentDetail.sharedElementReturnTransition = DetailTransition()
        activity?.apply {
            supportFragmentManager.beginTransaction()
                    .addSharedElement(icon, getString(R.string.transition_name_icon))
                    .addSharedElement(title, getString(R.string.transition_name_title))
                    .replace(R.id.container, fragmentDetail)
                    .addToBackStack(null)
                    .commit();
        }
    }

    private fun initData() {
        recyclerview?.adapter = adapter
        for (index in 1..10) {
            list.add(ListEntity(R.mipmap.ic_launcher, "item$index"))
        }
        adapter.setData(list)
    }
}
